package com.lanou3g.code0415.util;


import com.lanou3g.code0415.study.TestUUID;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
* 封装ServletUpload
* */
public class SmartUpload {
    private HttpServlet servlet;
    private ServletFileUpload sfu ;//用于上传
    private File uploadDir;
    //用来存储普通表单数据
    private HashMap<String,String>parameters;
    //用来存储上传的文件名和文件
    private HashMap<String,File>files;
    public SmartUpload(HttpServlet httpServlet){
        this.servlet=httpServlet;

        //初始化  上传文件夹
        initDir();
        //初始化 ServletFileUpload
        sfu=new ServletFileUpload();
        sfu.setFileItemFactory(new DiskFileItemFactory());
        //在构造方法中初始化
        parameters= new HashMap<>();
        files =new HashMap<>();
    }

    private void initDir() {
        String uploadPath=servlet.getServletContext()
                .getRealPath("")
                +File.separator+"upload";
        uploadDir = new File(uploadPath);
        if (!uploadDir.exists()){
            //创建文件夹
            uploadDir.mkdirs();
        }
    }
    public void parse(HttpServletRequest request){
        try {
            List<FileItem> fileItems=sfu.parseRequest(request);

            if (fileItems!=null){
                for (FileItem fileItem : fileItems) {

                    if (fileItem.isFormField()){
                        //表单数据
                        String key= fileItem.getFieldName();
                        String value=fileItem.getString("utf-8");

                        parameters.put(key,value);
                        //将数据加入到我们自己设的HashMap中
                    }else {
                        //不是表单数据 是文件
                        String fileName= fileItem.getName();
                        //引包  引的是Apache下的
                        //别导错了
                        if (StringUtils.isEmpty(fileName)){
                            continue;
                        }
                        String realName=TestUUID.handleFileName(fileName);

                        File file=new File(uploadDir,fileName);
                        fileItem.write(file);
                        files.put(fileName,file);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*提供 访问结果的方法*/
    public String getParameters(String key){
        return parameters.get(key);
    }
    public Map<String,String> getParameterMap(){
        return parameters;
    }
    public Map<String,File>getUploadedFiles(){
        return files;
    }
}
